package cn.com.inossem.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.foxykeep.datadroid.requestmanager.Request;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.uinfo.UserService;

import java.util.ArrayList;
import java.util.List;

import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.UserInfo;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.Utils;
import cn.com.inossem.utils.wangyi.session.SessionHelper;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 好友详情
 * <p>
 * <p>
 * detailed comment
 *
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
@RuntimePermissions
public class FriendsDetailsActivity extends RequestActivity {

	int type = 0;
	TextView zhuangtai, dizhi, endriqi, nicheng, sex, nickname, email;
	ImageView back, incopic;
	String phone;
	Button next;
	int fuid;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SessionHelper.init();
		// setContentView(R.layout.main_tab_layout);
		type = getIntent().getIntExtra("type", 0);
		phone = getIntent().getStringExtra("phone");
		toUserId = getIntent().getStringExtra("toUserId");
		toUserName = getIntent().getStringExtra("toUserName");
		initView();
		launchRequest(WooRequestFactory.friendsdetails(phone));
	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);
		incopic = (ImageView) this.findViewById(R.id.incopic);
		nicheng = (TextView) this.findViewById(R.id.nicheng);
		zhuangtai = (TextView) this.findViewById(R.id.zhuangtai);
		dizhi = (TextView) this.findViewById(R.id.dizhi);
		endriqi = (TextView) this.findViewById(R.id.endriqi);
		sex = (TextView) this.findViewById(R.id.sex);
		nickname = (TextView) this.findViewById(R.id.nickname);
		email = (TextView) this.findViewById(R.id.email);
		next = (Button) this.findViewById(R.id.next);
		next.setOnClickListener(this);
		Button chat = (Button) this.findViewById(R.id.chat);
		chat.setOnClickListener(this);
		if (type == 1) {
			next.setText("删除好友");
		} else {
			chat.setVisibility(View.GONE);
		}

	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	UserInfo userinfo = null;

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		if (bundle.containsKey(WooRequestFactory.BUNDLE_EXTRA_LOGIN)) {

			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_LOGIN) == 1) {
				enableChat = true;
				userinfo = bundle
						.getParcelable(WooRequestFactory.RESPONSE_LOGIN_DATA);
				if (!userinfo.getImageData().equals("")) {
					incopic.setBackgroundDrawable(new BitmapDrawable(Utils
							.toRoundCorner(
									stringtoBitmap(userinfo.getImageData()),
									300)));
				} else {
					incopic.setBackgroundDrawable(getResources().getDrawable(R.drawable.touxiang));
				}
				if (userinfo.getProjectStatus() == 0)
					zhuangtai.setText("");
				else
					zhuangtai.setText(selectData_info1("t_dictionary", "id="
							+ userinfo.getProjectStatus()));

				nicheng.setText(userinfo.getTruename());

				if (userinfo.getProjectStatus() == 10996) {
					dizhi.setText(selectData_info("t_areas",
							"area_id=" + userinfo.getProjectAddress()));
					endriqi.setText(userinfo.getProjectEndDate());
				}
				String userSex = userinfo.getSex();
				sex.setText(userSex.equals("0") ? "男" : "女");
				nickname.setText(userinfo.getNickname());
				email.setText(userinfo.getEmail());
				fuid = userinfo.getId();
				if (fuid == Utils.messageInfo.userInfo.getId()) {
					next.setVisibility(View.GONE);
				}
			} else {
				Toast.makeText(this, "没有当前账号！", Toast.LENGTH_LONG).show();
				finish();
			}

		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 1) {
				Toast.makeText(this, "添加好友成功,等待对方确认!", Toast.LENGTH_LONG)
						.show();
				setResult(1);
				finish();
			} else if (bundle
					.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 10) {
				Toast.makeText(this, "不能添加自己！", Toast.LENGTH_LONG).show();
			} else if (bundle
					.getInt(WooRequestFactory.BUNDLE_EXTRA_UPDATESUCCESS) == 11) {
				Toast.makeText(this, "已经是好友了！", Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, "添加好友失败！", Toast.LENGTH_LONG).show();
			}
		} else if (bundle
				.containsKey(WooRequestFactory.BUNDLE_EXTRA_DELSUCCESS)) {
			if (bundle.getInt(WooRequestFactory.BUNDLE_EXTRA_DELSUCCESS) == 1) {
				Toast.makeText(this, "删除好友成功！", Toast.LENGTH_LONG).show();
				finish();
			} else {
				Toast.makeText(this, "删除好友失败！", Toast.LENGTH_LONG).show();
			}
		}

	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.friendsdetails_layout;
	}

	boolean enableChat = false;
	String toUserId;
	String toUserName;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.back:
				finish();
				break;
			case R.id.next:
				if (type == 0) {
					launchRequest(WooRequestFactory.addfriends(phone));
				} else if (type == 1) {
					Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("确认删除吗？");
					builder.setTitle("提示");
					builder.setPositiveButton("确认", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							launchRequest(WooRequestFactory.delfriends(phone));
							if (null != Utils.messageInfo) {
								int friendNum = Integer.valueOf(Utils.messageInfo.userInfo.getFriendNum());
								if (friendNum > 0)
									Utils.messageInfo.userInfo.setFriendNum(String.valueOf(friendNum - 1));
							}
						}
					});
					builder.setNegativeButton("取消", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					builder.create().show();
				}
				break;
			case R.id.chat:
				if (enableChat) {
					FriendsDetailsActivityPermissionsDispatcher.startChatWithCheck(this);
				}
				break;
			default:
				break;
		}
	}

	@NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
	public void startChat() {
		List<String> accounts = new ArrayList<String>(1);
		accounts.add(fuid + "");
		NimUIKit.notifyUserInfoChanged(accounts);
		NIMClient.getService(UserService.class).getUserInfo(fuid + "");
		NimUIKit.startChatting(this, fuid + "", SessionTypeEnum.P2P, SessionHelper.getP2pCustomization());
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		FriendsDetailsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
			case 1:
				setResult(1);
				finish();
			default:
				break;
		}
	}

	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	private String selectData_info1(String tabname, String selection) {
		String name = "";
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("name_cn"));

		}
		cursor.close();
		db.close();
		dh.close();
		return name;
	}

	private String selectData_info(String tabname, String selection) {
		String name = "";
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		if (cursor.moveToFirst()) {
			name = cursor.getString(cursor.getColumnIndex("area_name"));

		}
		cursor.close();
		db.close();
		dh.close();
		return name;
	}
}
